//
//  MyCarUserInputView.m
//  SecondPage
//
//  Created by xiong qi on 13-5-13.
//  Copyright (c) 2013年 winston. All rights reserved.
//

#import "MyCarUserInputView.h"
#import "../../HondaPro_2/aejoy/NetworkService/NetworkManager.h"
#import "../../HondaPro_2/aejoy/Categories/NetworkingViewController.h"
//#import "../../Honda3/LoginView/LoginView.h"


@implementation MyCarUserInputView
@synthesize parentView,autoID;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        UILabel * cartypelabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 10, 50, 20)];
        cartypelabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
        cartypelabel.textAlignment = NSTextAlignmentLeft;
        cartypelabel.font = [UIFont fontWithName:@"Arial" size:12];
        [cartypelabel setBackgroundColor:[UIColor clearColor]];
        [self addSubview:cartypelabel];
        [cartypelabel release];
        cartypelabel.text = @"类型:";
        
        UILabel * namelabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 50, 50, 20)];
        namelabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
        namelabel.textAlignment = NSTextAlignmentLeft;
        namelabel.font = [UIFont fontWithName:@"Arial" size:12];
        [namelabel setBackgroundColor:[UIColor clearColor]];
        [self addSubview:namelabel];
        [namelabel release];
        namelabel.text = @"姓名:";
        
        
        UILabel * maillabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 90, 50, 20)];
        maillabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
        maillabel.textAlignment = NSTextAlignmentLeft;
        maillabel.font = [UIFont fontWithName:@"Arial" size:12];
        [maillabel setBackgroundColor:[UIColor clearColor]];
        [self addSubview:maillabel];
        [maillabel release];
        maillabel.text = @"邮箱:";
        
        
        UILabel * phonelabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 130, 50, 20)];
        phonelabel.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1.0];
        phonelabel.textAlignment = NSTextAlignmentLeft;
        phonelabel.font = [UIFont fontWithName:@"Arial" size:12];
        [phonelabel setBackgroundColor:[UIColor clearColor]];
        [self addSubview:phonelabel];
        [phonelabel release];
        phonelabel.text = @"手机:";
        
        cartypeselect = [[MyCarSelectMenuButton alloc] initWithFrame:CGRectMake(55, 5, 250, 30)];
        [self addSubview:cartypeselect];
        [cartypeselect release];
        
        
        _username = [[NameFiled alloc] initWithFrame:CGRectMake(55, 45, 250, 30)];
        [_username awakeFromNib];
        [self addSubview:_username];
        [_username release];
        _username.delegate = self;
        
        namevalidatelabel = [[UILabel alloc] initWithFrame:CGRectMake(310, 55, 10, 20)];
        [self addSubview:namevalidatelabel];
        [namevalidatelabel release];
        namevalidatelabel.text = @"*";
        [namevalidatelabel setBackgroundColor:[UIColor clearColor]];
        namevalidatelabel.textColor = [UIColor redColor];
        
        
        _usermail = [[NameFiled alloc] initWithFrame:CGRectMake(55, 85, 250, 30)];
        [_usermail awakeFromNib];
        [self addSubview:_usermail];
        _usermail.delegate = self;
        [_usermail release];
        
        
        userphone = [[NameFiled alloc] initWithFrame:CGRectMake(55, 125, 250, 30)];
        [userphone awakeFromNib];
        [self addSubview:userphone];
        [userphone release];
        userphone.delegate = self;
        

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    
    return self;
}

-(void)keyboardWillShow:(NSNotification *)notification
{
//    NSDictionary *info = [notification userInfo];
//    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    int height = 0;
    if ([_username isFirstResponder]) {
        height = 200;
    }
    else if([_usermail isFirstResponder]) {
        height = 240;
    }
    else if([userphone isFirstResponder]) {
        height = 280;
    }
    
    if(parentView != nil && [parentView respondsToSelector:@selector(ScrollViewToTop:)])
    {
        [parentView performSelector:@selector(ScrollViewToTop:) withObject:[NSNumber numberWithInt:height]];
    }
}

-(void)keyboardFrameChange:(NSNotification *)notification
{
    int height = 0;
    if ([_username isFirstResponder]) {
        height = 200;
    }
    else if([_usermail isFirstResponder]) {
        height = 240;
    }
    else if([userphone isFirstResponder]) {
        height = 280;
    }
    
    if(parentView != nil && [parentView respondsToSelector:@selector(ScrollViewToTop:)])
    {
        [parentView performSelector:@selector(ScrollViewToTop:) withObject:[NSNumber numberWithInt:height]];
    }
}

-(void)keyboardWillHide:(NSNotification *)notification
{
    if(parentView != nil && [parentView respondsToSelector:@selector(ScrollViewToTop:)])
    {
        [parentView performSelector:@selector(ScrollViewToTop:) withObject:[NSNumber numberWithInt:0]];
    }
}

-(void)RefreshCarType:(FavoriteModuleView *)moduleview
{
    NSString * selectstr = [NSString stringWithFormat:@"SELECT CarID,CarCode FROM CollocateParameterTable where CollocateID=%d",moduleview.selectIndex];
    
    NSArray * array = [[MyCarSQLHelp getInstance] GetTableData:selectstr];
    NSDictionary * templateDic = nil;
    NSString * key = @"";
    
    NSMutableArray * carinfos = [NSMutableArray array];
    if (array != nil && array.count >0) {
        templateDic = [array objectAtIndex:0];
        NSDictionary * car = nil;
        NSString * carids = [templateDic objectForKey:@"CarID"];
        NSString * carcodes = [templateDic objectForKey:@"CarCode"];
        NSArray  * caridsarray = [carids componentsSeparatedByString:@","];
        NSArray  * carcodesarray = [carcodes componentsSeparatedByString:@","];
        for (int i=0; i<caridsarray.count; i++) {
            if(i == 0)
            {
                key = [caridsarray objectAtIndex:i];
            }
            car = @{@"key": [caridsarray objectAtIndex:i],@"value":[carcodesarray objectAtIndex:i]};
            [carinfos addObject:car];
        }
        
    }
    cartypeselect.contentArray = carinfos;
    cartypeselect.currentKey = key;
    self.autoID = moduleview.autoID;
 
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    int height = 0;
    if (textField == _username) {
        height = 120;
    }
    else if(textField == _usermail) {
        height = 160;
    }
    else if(textField == userphone) {
        height = 200;
    }
    
    if(parentView != nil && [parentView respondsToSelector:@selector(ScrollViewToTop:)])
    {
        [parentView performSelector:@selector(ScrollViewToTop:) withObject:[NSNumber numberWithInt:height]];
    }
    
    return YES;
}

-(BOOL)CheckInputData
{
    if (_username.text == nil || [_username.text isEqualToString:@""]) {
        
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入姓名" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [alert show];
        SafeRelease(alert);
        return NO;
    }
    else if((userphone.text == nil ||[userphone.text isEqualToString:@""])&&(_usermail.text == nil ||[_usermail.text isEqualToString:@""]))
    {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:@"手机和邮箱不能同时为空" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [alert show];
        SafeRelease(alert);
        return NO;
    }
    
    
    return YES;
}

-(void)SendSaveData:(NSDictionary *)cardic
{
    if (![self CheckInputData]) {
        return;
    }
    
    NSMutableArray* favorites = [[[NSMutableArray alloc] init] autorelease];
//    NSDictionary* carKeyDic = @{@"carclass": self.autoID,
//                                @"cartype": cartypeselect.currentKey};
    NSMutableDictionary * carKeyDic = [NSMutableDictionary dictionaryWithDictionary:cardic];
    [carKeyDic setObject:self.autoID forKey:@"carclass"];
    [carKeyDic setObject:cartypeselect.currentKey forKey:@"cartype"];
    [favorites addObject:carKeyDic];
    
    //createDate
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone systemTimeZone];
    formatter.dateFormat = @"yyyy-MM-dd";
    NSString* createDateStr = [formatter stringFromDate:[NSDate date]];
    [formatter release];
    
//    NSDictionary* dic = @{@"salerID": [[LoginView shareInstance].salerInfo objectForKey:@"salerID"],
//                          @"name": _username.text == nil?@"":_username.text,
//                          @"createDate": createDateStr,
//                          @"mobile": userphone.text== nil?@"":userphone.text,
//                          @"email": _usermail.text== nil?@"":_usermail.text,
//                          @"favorites": favorites,
//                          @"level": @"2",
//                          @"source": @"A1",
//                          @"nature": @"C3",
//                          @"messagesource":@"1000010000"
//                          };
//    
//    
//    NetworkTask* MyCarFavoriteTask = [[NetworkTask alloc] initWithPostUrl:[NSString stringWithFormat:@"%@/RegisterIntentionCustomer.aspx", NetworkService_Server_DomainName] postArgs:dic];
//    MyCarFavoriteTask.indentifier = @"MyCarFavorite";
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onSuccessAboutCustomerInfo:) name:NetworkTask_NotificationName_OnSuccess object:MyCarFavoriteTask];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFailAboutCustomerInfo:) name:NetworkTask_NotificationName_OnFail object:MyCarFavoriteTask];
//    
//    [[NetworkManager getInstance] startTaskAsync:MyCarFavoriteTask];
//    SafeRelease(MyCarFavoriteTask);
}

- (void)onSuccessAboutCustomerInfo:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    if ([[task.resultDict objectForKey:@"error_code"] intValue] == 0) {
        [[NetworkingViewController sharedController] showNetworkingWithTitle:@"提示" content:@"保存成功" activiting:NO enableDismiss:YES];
        [[NetworkingViewController sharedController] performSelector:@selector(dismissNetworking) withObject:nil afterDelay:2];
    }
    else
    {
        [[NetworkingViewController sharedController] showNetworkingWithTitle:@"保存错误" content:[task.resultDict objectForKey:@"error_msg"] activiting:NO enableDismiss:YES];
    }
}

- (void)onFailAboutCustomerInfo:(NSNotification*)notify {
    NetworkTask* task = notify.object;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnSuccess object:task];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NetworkTask_NotificationName_OnFail object:task];
    
    //    NSString* error = [NSString stringWithFormat:@"%@",[task.resultDict objectForKey:@"error_msg"]];
    //    if ([task.indentifier isEqualToString:@"CustomerReceptionTask"]) {
    //        error = @"保存失败!";
    //    } else if ([task.indentifier isEqualToString:self.checkMobileBtn.restorationIdentifier]) {
    //        error = @"手机号查询失败!";
    //    } else if ([task.indentifier isEqualToString:self.checkNameBtn.restorationIdentifier]) {
    //        error = @"姓名查询失败";
    //    }
    
    [[NetworkingViewController sharedController] showNetworkingWithTitle:@"保存失败" content:@"请在良好的网络环境下操作，避免数据错误" activiting:NO enableDismiss:YES];
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.autoID = nil;
    self.parentView = nil;
    [super dealloc];
}

@end
